package com.camus.verify.algorithm.impl;

import java.math.BigDecimal;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Deque;

import com.camus.utils.BigDecimalUtils;
import com.camus.verify.algorithm.MatchTarget;
import com.camus.verify.algorithm.SubsetAlgorithm4BigDecimal;

public class SubsetAlgorithmOfSortPruningRecursion4BigDecimal2 implements SubsetAlgorithm4BigDecimal {

	@Override
	public MatchTarget[] findSubsetWithinRange(MatchTarget[] candidateArr, BigDecimal lower, BigDecimal upper) {
		// 先排序，方便后面有针对性地剪枝
		Arrays.sort(candidateArr, Comparator.comparing(MatchTarget::getTarget, BigDecimal::compareTo));

		int len = candidateArr.length;
		// 前缀和
		BigDecimal[] prefixSumArr = new BigDecimal[len];
		prefixSumArr[0] = candidateArr[0].getTarget();
		for (int i = 1; i < len; i++) {
			prefixSumArr[i] = prefixSumArr[i - 1].add(candidateArr[i].getTarget());
		}

		Deque<Integer> selectedIdxQueue = new ArrayDeque<>();
		// 逐层递归
		MatchTarget[] subsetArr = findSubsetWithinRange(candidateArr, lower, upper, prefixSumArr, selectedIdxQueue, 0,
				BigDecimal.ZERO);
		return subsetArr;
	}

	public MatchTarget[] findSubsetWithinRange(MatchTarget[] candidateArr, BigDecimal lower, BigDecimal upper,
			BigDecimal[] prefixSumArr, Deque<Integer> selectedIdxQueue, int candidateIdxBegin, BigDecimal curSum) {
		SubsetAlgorithm4BigDecimal.counter.get().getAndIncrement();
		int len = candidateArr.length;
		// 1.递归终止条件
		if (BigDecimalUtils.isWithinRange(curSum, upper, lower) == 0) {
			return filterSubset(candidateArr, selectedIdxQueue);
		}
		if (candidateIdxBegin >= len) {
			return null;
		}

		// 2.当前层逻辑：可以在[candidateIdxBegin,len)中选择一个
		for (int i = candidateIdxBegin; i < len; i++) {
			if (i > candidateIdxBegin && candidateArr[i].getTarget().compareTo(candidateArr[i - 1].getTarget()) == 0) {
				// 剪枝
				continue;
			}
			if (failFast(candidateArr, candidateIdxBegin, lower, upper, prefixSumArr)) {
				return null;
			}
			selectedIdxQueue.offerLast(i);

			// 3.递归调用下一层
			MatchTarget[] result = findSubsetWithinRange(candidateArr, lower, upper, prefixSumArr, selectedIdxQueue,
					i + 1, curSum.add(candidateArr[i].getTarget()));
			if (result != null) {
				return result;
			}

			// 4.回溯
			selectedIdxQueue.pollLast();
		}
		// 处理当层逻辑
		return null;
	}

	private MatchTarget[] filterSubset(MatchTarget[] candidateArr, Deque<Integer> selectedIdxQueue) {
		int len = selectedIdxQueue.size();
		if (len == 0) {
			return null;
		}
		MatchTarget[] subsetArr = new MatchTarget[len];
		int idx = 0;
		while (!selectedIdxQueue.isEmpty()) {
			subsetArr[idx++] = candidateArr[selectedIdxQueue.pollFirst().intValue()];
		}
		return subsetArr;
	}

	private boolean failFast(MatchTarget[] candidateArr, int candidateIdxBegin, BigDecimal lower, BigDecimal upper,
			BigDecimal[] prefixSumArr) {
		int len = candidateArr.length;
		if (candidateIdxBegin >= len) {
			return true;
		}
		BigDecimal min = candidateArr[candidateIdxBegin].getTarget();
		BigDecimal max = candidateArr[len - 1].getTarget();
		BigDecimal sum = prefixSumArr[len - 1]
				.subtract(candidateIdxBegin == 0 ? BigDecimal.ZERO : prefixSumArr[candidateIdxBegin - 1]);
		if (min.compareTo(BigDecimal.ZERO) >= 0) {
			// 所有元素都是正数
			if (BigDecimalUtils.isWithinRange(min, upper, lower) == 1) {
				// 且最小元素大于上边界
				return true;
			}
			if (BigDecimalUtils.isWithinRange(sum, upper, lower) == -1) {
				// 且所有元素之和仍然小于下边界
				return true;
			}
		}
		if (max.compareTo(BigDecimal.ZERO) <= 0) {
			// 所有元素都是负数，
			if (BigDecimalUtils.isWithinRange(max, upper, lower) == -1) {
				// 且最大元素小于下边界
				return true;
			}
			if (BigDecimalUtils.isWithinRange(sum, upper, lower) == 1) {
				// 且所有元素和仍然大于上边界
				return true;
			}
		}
		return false;
	}

}
